package com.tl.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tl.reggie.common.BaseContext;
import com.tl.reggie.common.R;
import com.tl.reggie.pojo.AddressBook;
import com.tl.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;

    @PostMapping
    public R<String> newAddress(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @PutMapping("/default")
    public R<AddressBook> defaultAddress(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        updateWrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(updateWrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    @GetMapping("/{id}")
    public R<AddressBook> getAddress(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook!=null){
            return R.success(addressBook);
        }
        return R.error("没有找到地址");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (addressBook!=null){
            return R.success(addressBook);
        }
        return R.error("没有找到默认地址");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> getAllAddress(AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getUserId()!=null,AddressBook::getUserId,addressBook.getUserId());
        return R.success(addressBookService.list(queryWrapper));
    }

    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
//        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
}
